package com.x.compute.common.function;

import com.googlecode.aviator.runtime.function.AbstractVariadicFunction;
import com.googlecode.aviator.runtime.function.FunctionUtils;
import com.googlecode.aviator.runtime.type.AviatorObject;
import com.googlecode.aviator.runtime.type.AviatorString;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 字符串拼接函数
 * 函数示例：JOIN(arg1, arg2, arg3, ...)
 * arg1-字符串分隔符，arg2-字符串/集合类型
 * @author xuxin
 */
public class JoinFunction extends AbstractVariadicFunction {

    @Override
    public String getName() {
        return "JOIN";
    }

    /**
     * 函数处理逻辑
     * @param env 变量上下文
     * @param args 参数集合
     * @return
     */
    @Override
    public AviatorObject variadicCall(Map<String, Object> env, AviatorObject... args) {
        String value = FunctionUtils.getStringValue(args[0], env);
        List<String> stringList = getStringList(env, args);
        return new AviatorString(String.join(value, stringList));
    }

    /**
     * 获取字符集
     * @param env
     * @param args
     * @return
     */
    private List<String> getStringList(Map<String, Object> env, AviatorObject... args){
        List<String> result = new ArrayList<>();
        for (int i = 1; i < args.length; i++) {
            Object value = args[i].getValue(env);
            if (value instanceof List){
                result.addAll((List) value);
            }else if (value instanceof Set){
                result.addAll(((Set) value));
            }else if (value instanceof Map){
                result.addAll(((Map) value).values());
            }else if (value instanceof String){
                result.add(value.toString());
            }
        }
        return result;
    }
}
